package com.ly.blog2Admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.ly.blog2Admin.config.security.JwtAuthenticatioToken;
import com.ly.blog2Admin.constant.SysConstants;
import com.ly.blog2Admin.controller.model.LoginBean;
import com.ly.blog2Admin.dao.model.SysLoginLog;
import com.ly.blog2Admin.dao.model.SysUser;
import com.ly.blog2Admin.service.SysLoginLogService;
import com.ly.blog2Admin.service.SysUserService;
import com.ly.blog2Admin.utils.PasswordUtils;
import com.ly.blog2Admin.utils.SecurityUtils;
import com.ly.blog2Common.core.http.ResponseMessage;
import com.ly.blog2Common.utils.IOUtils;
import com.ly.blog2Common.utils.IPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 登录控制器
 * @author Louis
 * @date Jan 14, 2019
 */
@RestController
public class SysLoginController {


	@Autowired
	private Producer producer;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private AuthenticationManager authenticationManager;
	@Autowired
	private SysLoginLogService sysLoginLogService;

	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		// 生成文字验证码
		String text = producer.createText();
		// 生成图片验证码
		BufferedImage image = producer.createImage(text);
		// 保存到验证码到 session
//		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
		// 保存到验证码到 servlet上下文
		request.getServletContext().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);	
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录接口
	 */
	@PostMapping(value = "/login")
	public JSONObject login(@RequestBody LoginBean loginBean, HttpServletRequest request) throws IOException {
		String username = loginBean.getAccount();
		String password = loginBean.getPassword();
		String captcha = loginBean.getCaptcha();
		// 从session中获取之前保存的验证码跟前台传来的验证码进行匹配
//		Object kaptcha = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		Object kaptcha = request.getServletContext().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		if(kaptcha == null){
			return ResponseMessage.error(304);
		}
		if(!captcha.equals(kaptcha)){
			return ResponseMessage.error(305);
		}
		// 用户信息
		SysUser user = sysUserService.findByName(username);
		// 账号不存在、密码错误
		if (user == null) {
			return ResponseMessage.error(301);
		}
		if (!PasswordUtils.matches(user.getSalt(), password, user.getPassword())) {
			return ResponseMessage.error(302);
		}
		// 账号锁定
		if (user.getStatus() != null && user.getStatus() == 0) {
			return ResponseMessage.error(310);
		}
		// 系统登录认证
		JwtAuthenticatioToken token = SecurityUtils.login(request, username, password, authenticationManager);

		sysLoginLogService.saveLoginLog(username,IPUtils.getIpAddr(request));

		//组建用户信息返回 , 抹除敏感信息
		user.setPassword("");
		user.setSalt("");

		Map<String,Object> userInfo = new HashMap<>();
		userInfo.put("token",token.getToken());
		userInfo.put("user",user);
		return ResponseMessage.ok(userInfo);
	}


	/**
	 * 登出接口
	 */
	@GetMapping("/userLogout") // logout 存在冲突
	public JSONObject logout( HttpServletRequest request) throws IOException {

		String username = SecurityUtils.getUsername();
		sysLoginLogService.saveLogoutLog(username,IPUtils.getIpAddr(request),SysLoginLog.LOGIN_STATE_LOGOUT);

		return ResponseMessage.ok();
	}


	@PostMapping(value="/register")
	public JSONObject register(@RequestBody SysUser record) {
		SysUser user = sysUserService.findById(record.getId());
		if(user != null) {
			if(SysConstants.ADMIN.equalsIgnoreCase(user.getName())) {
				return ResponseMessage.error(306);
			}
		}
		if(record.getPassword() != null) {
			String salt = PasswordUtils.getSalt();
			if(user == null) {
				// 新增用户
				if(sysUserService.findByName(record.getName()) != null) {
					return ResponseMessage.error(303);
				}
				String password = PasswordUtils.encode(record.getPassword(), salt);
				record.setSalt(salt);
				record.setPassword(password);
			} else {
				// 修改用户, 且修改了密码
				if(!record.getPassword().equals(user.getPassword())) {
					String password = PasswordUtils.encode(record.getPassword(), salt);
					record.setSalt(salt);
					record.setPassword(password);
				}
			}
		}
		return ResponseMessage.ok(sysUserService.save(record));
	}

	public static void main(String[] args) {
		int a = new Random().nextInt(100000);
		int b = new Random().nextInt(10);

		System.out.printf("" + b +a);

	}

}
